package com.icode.core.shared;

import com.icode.core.alipay.util.AlipayNotify;
import com.icode.core.alipay.util.AlipaySubmit;
import com.icode.core.model.order.Order;
import com.icode.core.model.order.ReFund;
import com.icode.service.order.OrderService;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: xianfei
 * Date: 15-2-6
 * Time: 下午1:31
 * To change this template use File | Settings | File Templates.
 */
public class AlipayHandle {


    public static void alipay(Order order, PrintWriter out) {
        //即时到账支付入口
        //支付类型,必填，不能修改
        String payment_type = "1";
        //服务器异步通知页面路径
//        String notify_url = "http://www.mantingv.com/order/notify_url";
        String notify_url = "http://127.0.0.1:8080/order/notify_url";
        //需http://格式的完整路径，不能加?id=123这类自定义参数		//页面跳转同步通知页面路径
//       String return_url = "http://www.mantingv.com/order/return_url";
        String return_url = "http://127.0.0.1:8080/order/return_url";
        //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/		//卖家支付宝帐户
        String seller_email = "897723229@qq.com";
        //商s户订单号,商户网站订单系统中唯一订单号，必填
        String out_trade_no = order.guid();
        //订单名称
        String subject = order.houseInfo().guid().substring(0,6);
        //付款金额
        String total_fee = order.orderInfo().totalPrice();
        //需以http://开头的完整路径，例如：http://www.商户网址.com/myorder.html		//防钓鱼时间戳
        String anti_phishing_key = "";
        //若要使用请调用类文件submit中的query_timestamp函数		//客户端的IP地址
        String exter_invoke_ip = "";
        //非局域网的外网IP地址，如：221.0.0.1

        //把请求参数打包成数组
        Map<String, String> sParaTemp = new HashMap<>();
        sParaTemp.put("service", "create_direct_pay_by_user");
        sParaTemp.put("partner", "2088811444079415");
        sParaTemp.put("_input_charset", "utf-8");
        sParaTemp.put("payment_type", payment_type);
        sParaTemp.put("notify_url", notify_url);
        sParaTemp.put("return_url", return_url);
        sParaTemp.put("seller_email", seller_email);
        sParaTemp.put("out_trade_no", out_trade_no);
        sParaTemp.put("subject", subject);
        sParaTemp.put("total_fee", total_fee);
        sParaTemp.put("anti_phishing_key", anti_phishing_key);
        sParaTemp.put("exter_invoke_ip", exter_invoke_ip);
        String sHtmlText = AlipaySubmit.buildRequest(sParaTemp, "get", "确认");
        out.println(sHtmlText);
    }

    public static void reFund(PrintWriter out, String detail_data) {
        String notify_url = "http://www.mantingv.com/order/refundNotify_url";
        String batch_num = "1";
        //把请求参数打包成数组
        Map<String, String> sParaTemp = new HashMap<>();
        sParaTemp.put("service", "refund_fastpay_by_platform_pwd");
        sParaTemp.put("partner", "2088811444079415");
        sParaTemp.put("_input_charset", "utf-8");
        sParaTemp.put("notify_url", notify_url);
        sParaTemp.put("seller_email", "897723229@qq.com");
        sParaTemp.put("refund_date", JodaTimeUtils.getTime("yyyy-MM-dd HH:mm:ss"));
        sParaTemp.put("batch_no", JodaTimeUtils.getTime("yyyyMMddHHmmss") + JodaTimeUtils.getSerial());
        sParaTemp.put("batch_num", batch_num);
        sParaTemp.put("detail_data", detail_data);
        //建立请求
        String sHtmlText = AlipaySubmit.buildRequest(sParaTemp, "post", "确认");
        out.println(sHtmlText);
    }

    public static void batchRefund(PrintWriter out, String detail_data, String batch_num) {
        String notify_url = "http://www.mantingv.com/order/refundNotify_url";
        String seller_email = "897723229@qq.com";
        //把请求参数打包成数组
        Map<String, String> sParaTemp = new HashMap<>();
        sParaTemp.put("service", "refund_fastpay_by_platform_pwd");
        sParaTemp.put("partner", "2088811444079415");
        sParaTemp.put("_input_charset", "utf-8");
        sParaTemp.put("notify_url", notify_url);
        sParaTemp.put("seller_email", seller_email);
        sParaTemp.put("refund_date", JodaTimeUtils.getTime("yyyy-MM-dd HH:mm:ss"));
        sParaTemp.put("batch_no", JodaTimeUtils.getTime("yyyyMMddHHmmss") + JodaTimeUtils.getSerial());
        sParaTemp.put("batch_num", batch_num);
        sParaTemp.put("detail_data", detail_data);
        //建立请求
        String sHtmlText = AlipaySubmit.buildRequest(sParaTemp, "post", "确认");
        out.println(sHtmlText);
    }

    public static void refundNotify_url(HttpServletRequest request, OrderService orderService, PrintWriter out) {
        //即时到账退款接口返回通知
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            params.put(name, valueStr);
        }

        String result_details = "";
        try {
            result_details = new String(request.getParameter("result_details").getBytes("UTF-8"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String trade_no = result_details.substring(0, result_details.indexOf("^"));
        ReFund reFund = orderService.findReFundByTradeNo(trade_no);
        if (AlipayNotify.verify(params)) {//验证成功
            orderService.changeReFundStatusByGuid(reFund.guid(), "已退款");
            orderService.changeOrderStatusByGuid(reFund.order().guid(), "已退款");
            out.println("success");
        } else {//验证失败
            orderService.changeReFundStatusByGuid(reFund.guid(), "退款失败");
            orderService.changeOrderStatusByGuid(reFund.order().guid(), "退款失败");
            out.println("fail");
        }
    }

    public static Map<String, Object> return_url(HttpServletRequest request, OrderService orderService, PrintWriter out) {
        //即时到账支付接口返回
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            params.put(name, valueStr);
        }
        String out_trade_no = null;
        String trade_no = "";
        String trade_status = "";
        try {
            out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        boolean verify_result = AlipayNotify.verify(params);
        if (verify_result) {//验证成功
            orderService.paySuccessOrderByGuid(out_trade_no, trade_no);
            if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
            }
            out.println("success");
        } else {
            out.println("fail");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("success", true);
        map.put("orderGuid", out_trade_no);
        return map;
    }

    public static void notify_url(HttpServletRequest request, OrderService orderService, PrintWriter out) {
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
//            try {
//                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
            params.put(name, valueStr);
        }
        String out_trade_no = "";
        String trade_no = "";
        String trade_status = "";
        try {
            out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (AlipayNotify.verify(params)) {//验证成功
            if (trade_status.equals("TRADE_FINISHED")) {

            } else if (trade_status.equals("TRADE_SUCCESS")) {
                orderService.paySuccessOrderByGuid(out_trade_no, trade_no);
            }
            out.println("success");
        } else {//验证失败
            out.println("fail");
        }
    }

    public static String getDetailData(String[] guids, OrderService orderService) {
        String detailData = "";
        for (int i = 0; i < guids.length; i++) {
            ReFund reFund = orderService.findReFundByGuid(guids[i]);
            detailData += (i == guids.length - 1) ? reFund.detailData() : reFund.detailData() + "#";
        }
        return detailData;
    }


}
